//
//  CS_MusicManager.swift
//  NewSS
//
//  Created by 杨馥瑞 on 2021/9/9.
//

import UIKit

let musicManagerQueue = DispatchQueue(label: "com.music.manager.serial.queue")

class CS_MusicManager {
    
    enum SoundType: Int {
        /// "原生","深情","空灵","K歌"
        case raw,soulful,ethereal,Karaoke
    }
    
    static let shared = CS_MusicManager()
    let musicListDidUpdatedNotificationName = "music_list_updated_notification"
    
    /// 存放在数据库中的音乐模型
    private(set) var musicList: [CS_MusicModel] = [CS_MusicModel]()
    private(set) var currentSoundEffect: SoundType = .soulful
    
    private init() {
        setup(identifier: "room_music")
    }
    
    // MARK: - 外部方法
    
    func setup(identifier: String) {
        CS_MusicStorageManager.shared.setup(identifier: identifier)
        
        musicList = loadLocalMusic()
    }
    
    func addMusic(_ music: CS_MusicModel) {
        addMusicArray([music])
    }
    
    func addMusicArray(_ musicArray: [CS_MusicModel]) {
        guard !musicArray.isEmpty else { return }
        DispatchQueue.main.async {
            CS_MusicStorageManager.insertMusicArray(musicArray)
            self.musicList = self.loadLocalMusic()
            self._notifyMusicListDidUpdated()
        }
    }
    
    func updateMusic(_ music: CS_MusicModel) {
        addMusic(music)
    }
    
    func updateMusic(_ musicArray: [CS_MusicModel]) {
        addMusicArray(musicArray)
    }
    
    func removeMusic(_ music: CS_MusicModel) {
        removeMusicArray([music])
    }
    
    func removeMusicArray(_ musicArray: [CS_MusicModel]) {
        guard !musicArray.isEmpty else { return }
        // 删除数据库中的索引
        DispatchQueue.main.async {
            CS_MusicStorageManager.deleteMusicArray(musicArray.map { $0.identifier })
            self.musicList = self.loadLocalMusic()
            self._notifyMusicListDidUpdated()
        }
        
        // 删除文件
        DispatchQueue.global().async {
            CS_MusicWifiFileStorage.shared.removeFileNames(musicArray.map { $0.musicName })
            CS_AccompanyManager.shardInstance.deleteMusics(musicArray)
        }
    }
    
    /// 已经存在音乐文件的音乐
    func queryAllMusics() -> [CS_MusicModel] {
        var result = [CS_MusicModel]()
        var needDeleteMusics = [CS_MusicModel]()
        for music in CS_MusicStorageManager.queryAllMusicAndSortByCreateTime() {
            if music.fileExist {
                result.append(music)
            }
            else {
                needDeleteMusics.append(music)
            }
        }
        CS_MusicManager.shared.removeMusicArray(needDeleteMusics)
        return result
    }
    
    /// 改变音效，调整音效成功之后设置
    func changeCurrentSoundEffectTo(_ newEffect: CS_MusicManager.SoundType) {
        currentSoundEffect = newEffect
    }
        
    func clear() {
        CS_MusicStorageManager.shared.clearDatabaseInfo()
        musicList.removeAll()
    }
    
    // MARK: - 私有方法
    
    private func loadLocalMusic() -> [CS_MusicModel] {
        return CS_MusicStorageManager.queryAllMusicAndSortByCreateTime()
    }
    
    private func _notifyMusicListDidUpdated() {
        NotificationCenter.default.post(name: NSNotification.Name(musicListDidUpdatedNotificationName), object: musicList)
    }

}


